package newtank.network.server.registry;

import io.netty.channel.ChannelHandlerContext;
import newtank.data.AbstractDataPackage;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author lijiahao
 * @since 2022/3/8
 */
public class ChannelRegistry {

    private static final Map<String, ChannelHandlerContext> CTX_MAP = new HashMap<>();

    public static void registry(String unique, ChannelHandlerContext ctx) {
        CTX_MAP.putIfAbsent(unique, ctx);
    }

    public static void inform(AbstractDataPackage informPackage) {
        CTX_MAP.forEach((unique, ctx) -> {
            if(!Objects.equals(informPackage.getUnique(), unique)) {
                ctx.writeAndFlush(informPackage);
            }
        });
    }

    public static void informAll(AbstractDataPackage informPackage) {
        CTX_MAP.forEach((unique, ctx) -> ctx.writeAndFlush(informPackage));
    }

    public static void inform(String unique, AbstractDataPackage informPackage) {
        ChannelHandlerContext ctx = CTX_MAP.getOrDefault(unique,  null);
        if(ctx != null) {
            ctx.writeAndFlush(informPackage);
        }
    }
}
